<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>webSocket</title>
    <style type="text/css">
        .box{padding:5px;}
        label{display:inline-block;width:70px;vertical-align:top;}
        input{border:1px solid #ddd;outline:none;height:25px;line-height:25px;border-radius:3px;width:300px;}
        button{display:inline-block;height:30px;line-height:30px;padding:0px 10px;font-size:16px;
            border: 1px solid #eee;border-radius:3px;outline:none;background:lightgreen;color:#fff;
        }
        textarea{width:500px;height:400px;resize:none;outline:none;border:1px solid #999;border-radius:3px;}
    </style>
</head>
<body>
<h2>hello,websocket.</h2>
<div class="box">
    <label>username:</label>
    <input id="sid" type="text"/>
    <button  onclick="connect()">connect</button>
</div>
<div class="box">
    <label>content:</label>
    <input id="message" type="text"/>
    <button onclick="send()">send</button>
</div>
<div class="box">
    <label>response:</label>
    <textarea id="response"></textarea>
</div>
</body>
<script type="text/javascript">
    var socket;
    window.onload = function(){

    }

    function $(id){
        return document.getElementById(id);
    }

    function connect(){
        if(typeof(WebSocket)=="undefined"){
            alert("your browser not supported websocket.")
        }else{
            var sid = $("sid").value;
            var url = "ws://localhost:8081/webSocket/"+sid;

            if(socket!=null){
                socket.close();
                socket = null;
            }

            socket = new WebSocket(url)

            socket.onopen = function(){
                $("response").value = "connect successfully.\r\n";
            }

            socket.onmessage = function(message){
                $("response").value += message.data+"\r\n";
            }

            socket.onclose = function(){
                $("response").value += "close websocket.\r\n";
            }

            socket.onerror = function(){
                $("response").value += "websocket on error.\r\n";
            }
        }
    }

    function send(){
        var message = $("message").value;
        if(message == "" || message == null){
            alert("message could't be null.")
        }
        socket.send(message)
    }
</script>
</html>